package com.ncut.gateway.filter;

import com.ncut.constant.JwtClaimsConstant;
import com.ncut.properties.JwtProperties;
import com.ncut.utils.JwtUtil;
import com.ncut.gateway.config.AuthProperties;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @FileName AuthGlobalFilter
 * @Description
 * @Author Sword
 * @date 2025-08-08
 **/

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthProperties authProperties;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        String path = request.getPath().toString();
        if (isExclude(path)) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }

        // 3.获取请求头中的token
        List<String> headers = request.getHeaders().get("token");
        // 4.校验并解析token
        String token = null;
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }

        Long empId = null;
        Long userId = null;

        //判断是哪个端的请求
        //管理端
        try {
            if (path.contains("admin")) {
                empId = getId(jwtProperties.getAdminSecretKey(), token, JwtClaimsConstant.EMP_ID);
            } else if (path.contains("user")) {
                userId = getId(jwtProperties.getUserSecretKey(), token, JwtClaimsConstant.USER_ID);
            }
        } catch (Exception e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //5.如果有效，传递用户信息
        ServerWebExchange swe = null;

        if (userId != null) {
            String userInfo = userId.toString();
            swe = exchange.mutate()
                    .request(builder -> builder.header("user-info", userInfo))
                    .build();
        } else if (empId != null) {
            String empInfo = empId.toString();
            swe = exchange.mutate()
                    .request(builder -> builder.header("emp-info", empInfo))
                    .build();
        }
        // 6.放行
        return chain.filter(swe);
    }

    private Long getId(String SecretKey, String token, String key) {
        Claims claims = JwtUtil.parseJWT(SecretKey, token);
        Long id = Long.valueOf(claims.get(key).toString());
        return id;
    }

    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();

        for (String excludePath : excludePaths) {
            if (pathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
